

import 'dart:developer';
import 'dart:ffi';
import 'dart:io';
import 'dart:typed_data';

import 'package:flutterapp/data.pb.dart';
import 'package:image_picker/image_picker.dart';
import 'package:udp/udp.dart';

class Sender{
  late XFile? xfile;
  late File? file;
  late UDP udpClient;
  late Endpoint remote;
  late int id;

  int chunkLen=30000;
  int maxLen=0;
  int maxIndexLen=0;

  Sender(this.udpClient,this.remote, this.xfile,this.file){
    if(xfile!=null && file!=null){
      throw ArgumentError('请不要同时设置2个文件');
    }
    if(xfile==null && file==null){
      throw ArgumentError('文件不存在');
    }
    final now = DateTime.now();
    id=now.millisecond+now.hour+now.minute+now.second+now.day+now.month+now.year;
  }

  //发送内容
  Future<bool> send(int index) async{
    if(maxIndexLen>0 && index>=maxIndexLen){
      return false;
    }
    log('send index=$index');
    if(xfile!=null){
      maxLen =await xfile!.length();
      maxIndexLen=(maxLen/chunkLen).ceil();
      var response = xfile!.openRead(index*chunkLen,(index+1)*chunkLen);
      var result= await response.first;
      var pack = FileChunkPack(id: id,chunk: result,len: maxLen,name: xfile!.name,packIndex:index,packLen: maxIndexLen );
      var buffer = MsgPack(type: 2,chunk: pack.writeToBuffer()).writeToBuffer();
      var l =await udpClient.send(buffer, remote);
      if(l!=buffer.length){
        log('发送长度不一致 $l <=> ${buffer.length}');
        return await send(index);
      }
      return true;
    }
    if(file!=null){
      maxLen =await file!.length();
      maxIndexLen=(maxLen/chunkLen).ceil();
      var response = file!.openRead(index*chunkLen,(index+1)*chunkLen);
      var result= await response.first;
      var fileName = file!.path.replaceAll(file!.parent.path, '').replaceAll('/', '').replaceAll('\\', '');
      var pack = FileChunkPack(id: id,chunk: result,len: maxLen,name: fileName,packIndex:index,packLen: maxIndexLen );
      var buffer = MsgPack(type: 3,chunk: pack.writeToBuffer()).writeToBuffer();
      var l =await udpClient.send(buffer, remote);
      if(l!=buffer.length){
        log('发送长度不一致 $l <=> ${buffer.length}');
        return await send(index);
      }
      return true;
    }
    return false;
  }



}